<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\index\service;

use app\index\model\AliSmsTemplate;
use app\index\model\MsgTemplate;
use app\index\model\WechatTemplate;
use app\index\model\Configuration;
use app\utils\AliSms;
use think\Exception;
use think\facade\Config;
use think\Model;
use WeChat\Template as WxTemplate;
use WeMini\Template as WxaTemplate;

class SendMsgService
{

    private $scene;
    private $scenarized;
    private $type;

    public function __construct($type)
    {
        //获取场景商城变量
        $load = Config::load('extension/scene', 'scene');
        //endregion
        $this->scene = $load[$type];
        $this->type = $type;
    }

    public function send($user, $data, $url = null)
    {
        $msgTemplateList = MsgTemplate::where(['type' => $this->type, "status" => 1])->select();
        foreach ($msgTemplateList as $k => $v) {
            switch ($v->channel) {
                case 1:
                    $this->sendWxMsg($v, $user->userWx->openid, $data, $url);
                    break;
                case 2:
                    $this->sendWxaMsg($user->userWx->openid, $data, $url);
                    break;
                case 3:
                    $this->sendAliMsg($v, $user->mobile, $data);
                    break;
            }
        }
        return true;

    }

    private function sendAliMsg($msgTemplate, $mobile, $data)
    {
        $aliSmsTemplate = AliSmsTemplate::find($msgTemplate->template_id);
        $attr = [];
        foreach ($aliSmsTemplate->attr as $k => $v) {
            $attr[$k] = $data[$this->scene[$v]];
        }
        $data = array_merge(
            [
                'RegionId' => "cn-hangzhou",
                'PhoneNumbers' => $mobile,
                'SignName' => $aliSmsTemplate->sign_name,
                'TemplateCode' => $aliSmsTemplate->template_code,
            ], ["TemplateParam" => json_encode($attr)]);
        try {
            $aliSms = new AliSms();
        } catch (\Exception $e) {
            return false;
        }
        return $aliSms->SendSms($data);
    }

    private function sendWxaMsg($openid, $data, $url)
    {
        //获取微信配置
        $configuration = Configuration::where(['type' => 'wxa', 'status' => 1])->value('configuration');
        if (empty($configuration))
            return false;
        //获取模板配置
        $templateData = $this->getBaseTemplate(2, $openid, $data, $url);
        //获取模板实例
        $template = new WxaTemplate($configuration);
        return $template->send($templateData);
    }


    private function sendWxMsg(Model $msgTemplate, string $openid, array $data, ?string $url)
    {
        //获取微信配置
        $configuration = Configuration::where(['type' => 'wx', 'status' => 1])->value('configuration');
        if (empty($configuration))
            return false;

        //获取模板配置
        if (empty($msgTemplate->is_base)) { //默认模板
            $templateData = $this->getBaseTemplate(1, $openid, $data, $url);
        } else { //非默认模板
            $wechatTemplate = WechatTemplate::find($msgTemplate->template_id);
            if (empty($wechatTemplate))
                return false;
            $templateData = $this->getTemplate($wechatTemplate, $openid, $data, $url);
        }
        //获取模板实例
        $template = new WxTemplate($configuration);
        return $template->send($templateData);
    }

    private function getBaseTemplate(int $channel, string $openid, array $data, ?string $url)
    {
        //获取基础模板列表
        $this->scenarized = Config::load('extension/scenarized', 'scenarized');

        //整理模板数据
        $template = $this->scenarized[$this->type][$channel];
        $template['touser'] = $openid;
        $template['url'] = $url;

        foreach ($template['data'] as $k => $v) {
            $template[$k]['value'] = $data[$this->scene[$v['value']]];
        }
        return $template;
    }


    private function getTemplate(Model $wechatTemplate, string $openid, array $data, ?string $url)
    {
        //设置模板数据
        $template = [
            "touser" => $openid,
            "template_id" => $wechatTemplate->template_id,
            "url" => $url,
        ];
        //设置模板内的data内的first数据
        $data = [
            "first" => [
                "value" => $data[$this->scene[$wechatTemplate->first->value]],
                'color' => $wechatTemplate->first->color
            ]
        ];

        //整合data内attr数据
        if (!empty($wechatTemplate->attr)) {
            $attr = [];
            foreach ($wechatTemplate->attr as $k => $v) {
                $attr[$k] = [
                    "value" => $data[$this->scene[$v->value]],
                    'color' => $v->color

                ];
            }
            $data = array_merge($data, $attr);

        }

        //整合data内remark数据
        if (!empty($wechatTemplate->remark)) {
            $remark = [
                "value" => $data[$this->scene[$wechatTemplate->remark->value]],
                'color' => $wechatTemplate->remark->color
            ];
            $data = array_merge($data, $remark);
        }
        $template['data'] = $data;
        return $template;
    }


}